package service;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import Dao.GetMarksAndInfoDao;
import bean.MarksAndInfoBody;

/**
 * Servlet implementation class GetMarkService
 */
public class GetMarkService extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public GetMarkService() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	
		
	} 

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String contents=request.getParameter("contents").toString();
		response.setContentType("text/html;charset=utf-8");
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		PrintWriter writer = response.getWriter();
		
		List<Map<String,Object>> mapList=new ArrayList<Map<String,Object>>();
		List<MarksAndInfoBody> resultBody=new ArrayList<MarksAndInfoBody>();
		JSONArray jsonArray =JSONArray.fromObject(contents);
		for(int i=0;i<jsonArray.size();i++){
			Map<String,Object> map=new HashMap<String,Object>();
			JSONObject object=(JSONObject) jsonArray.get(i);
			map.put("id", object.get("userid"));
			map.put("distance",object.get("distance"));
//			temp.setLatitude(mapList.get(i).get("latitude").toString());
//			temp.setLongitude(mapList.get(i).get("longitude").toString());
			map.put("latitude",object.get("latitude").toString());
			map.put("longitude",object.get("longitude").toString());
			mapList.add(map);
		}
		GetMarksAndInfoDao dao=new GetMarksAndInfoDao();
		
		resultBody=dao.getInfo(mapList);
		int status=1;
		JSONArray jsonArrayResult=new JSONArray();
		for(int j=0;j<resultBody.size();j++){
			if(resultBody.get(j).getStatus()!=1){
				status=resultBody.get(j).getStatus();
			}
			JSONObject json= JSONObject.fromObject(resultBody.get(j));
			jsonArrayResult.add(json);
		}
		JSONObject resultJSON=new JSONObject();
		resultJSON.put("jsonArrayResult", jsonArrayResult);
		resultJSON.put("status", status);
		writer.println(resultJSON.toString());
		writer.flush();
		writer.close();
	}

}
